<template>
  <el-card>
    <el-form inline @submit.prevent>
      <el-form-item>
        <el-input placeholder="用户名" v-model="searchUsername"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button :icon="Search" type="primary" @click="searchWithUsername"
          >查询</el-button
        >
        <el-button @click="clearSearchUsername">清空</el-button>
      </el-form-item>
    </el-form>
    <el-button type="primary" @click="addUser">添加</el-button>
    <el-button type="danger" :disabled="isDisable" @click="batchRemove"
      >批量删除</el-button
    >

    <el-table
      :data="userList"
      border
      class="my-20"
      v-loading="isLoading"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        type="selection"
        width="55"
        align="center"
      ></el-table-column>
      <el-table-column
        type="index"
        label="序号"
        width="65"
        align="center"
      ></el-table-column>
      <el-table-column label="用户名" prop="username" />
      <el-table-column label="用户昵称" prop="nickName" />
      <el-table-column label="角色列表" prop="roleName" />
      <el-table-column label="创建时间" prop="gmtCreate" />
      <el-table-column label="更新时间" prop="gmtModified" />
      <el-table-column label="操作" align="center" width="200">
        <template #default="{ row }">
          <el-tooltip content="分配角色" placement="top" effect="light">
            <el-button
              :icon="UserFilled"
              type="info"
              size="small"
              @click="assignRoles(row.id, row.username)"
            ></el-button
          ></el-tooltip>
          <el-tooltip content="编辑用户" placement="top" effect="light">
            <el-button
              :icon="Edit"
              type="primary"
              size="small"
              @click="editUser(row.id, row.username)"
            ></el-button>
          </el-tooltip>
          <el-tooltip content="删除用户" placement="top" effect="light">
            <div class="inline-block">
              <el-popconfirm
                :title="`确定删除<${row.username}>吗？`"
                @confirm="deleteUser(row.id)"
              >
                <template #reference>
                  <el-button
                    :icon="Delete"
                    type="danger"
                    size="small"
                  ></el-button
                ></template>
              </el-popconfirm>
            </div>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-model:currentPage="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[5, 10, 20, 30, 40]"
      small
      :disabled="false"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <!-- 添加用户的对话框 -->
    <el-dialog v-model="visible" title="添加用户" @closed="clearAll">
      <el-form
        ref="addUserFormRef"
        :rules="addUserFormRules"
        label-width="120px"
        :model="userInfo"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userInfo.username" />
        </el-form-item>
        <el-form-item label="用户昵称" prop="nickName">
          <el-input v-model="userInfo.nickName"></el-input>
        </el-form-item>
        <el-form-item label="用户密码" prop="password">
          <el-input v-model="userInfo.password"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="visible = false">取消</el-button>
          <el-button type="primary" @click="saveUser">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 设置用户角色的对话框 -->
    <el-dialog
      v-model="assignRoleVisible"
      title="设置角色"
      @closed="clearRoleInfo"
    >
      <el-form label-width="120px">
        <el-form-item label="用户名">
          <el-input disabled v-model="roleUser" />
        </el-form-item>
        <el-form-item label="角色列表">
          <el-checkbox
            v-model="checkAll"
            :indeterminate="isIndeterminate"
            @change="handleCheckAllChange($event as boolean)"
            >全选</el-checkbox
          >
          <div style="width: 100%"></div>
          <el-checkbox-group v-model="selectedRoles">
            <!-- @change="handleCheckedRolesChange" -->
            <el-checkbox
              v-for="role in allRolesList"
              :key="role.id"
              :label="role.id"
              >{{ role.roleName }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="assignRoleVisible = false">取消</el-button>
          <el-button type="primary" @click="assignRoleToUser">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 修改用户的对话框 -->
    <el-dialog v-model="editUserVisible" title="修改用户">
      <el-form
        label-width="120px"
        :rules="updateUserFormRules"
        :model="updateUserForm"
        ref="updateUserFormRef"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="updateUserForm.username" />
        </el-form-item>
        <el-form-item label="用户昵称">
          <el-input v-model="updateUserForm.nickName" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editUserVisible = false">取消</el-button>
          <el-button type="primary" @click="updateUser">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>
</template>

<script lang="ts">
export default {
  name: 'ZUser',
}
</script>

<script lang="ts" setup>
import { Search, UserFilled, Edit, Delete } from '@element-plus/icons-vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ref, onMounted, reactive, watch } from 'vue'

import {
  getUserListApi,
  userSaveApi,
  getUserRolesApi,
  assignRolesToUserApi,
  updateUserApi,
  deleteUserApi,
  batchRemoveApi,
} from '@/api/userController/userControllerApi'
import type {
  ItemsType,
  Role,
} from '@/api/userController/model/userControllerApiModel'
import { ElMessage } from 'element-plus'

const isLoading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(1)
const userList = ref<ItemsType[]>([])
const visible = ref(false)
const searchUsername = ref('')
const addUserFormRef = ref<FormInstance>()
const userInfo = reactive({
  username: '',
  nickName: '',
  password: '',
})

const assignRoleVisible = ref(false)
const checkAll = ref(false)
const isIndeterminate = ref(false)
const allRolesList = ref<Role[]>([])
const selectedRoles = ref<string[]>([])
const roleUser = ref('')
const userId = ref(0)

const batchRemoveIdList = ref<string[]>([])
const isDisable = ref(true)
// 批量删除
const batchRemove = async () => {
  const data = [...batchRemoveIdList.value]
  const params = data.map((item) => +item)
  await batchRemoveApi(params)
  ElMessage.success('批量删除成功')
  getUserList()
}

// 勾选框
const handleSelectionChange = (userList: ItemsType[]) => {
  batchRemoveIdList.value = userList.map((user) => user.id)
  isDisable.value = !batchRemoveIdList.value.length
}

// 删除用户
const deleteUser = async (id: number) => {
  await deleteUserApi(id)
  ElMessage.success('删除成功')
  getUserList()
}

const editUserVisible = ref(false)
const updateUserForm = reactive({
  nickName: '',
  username: '',
  id: -100,
})
const updateUserFormRef = ref<FormInstance>()
// 用户名的表单验证
const usernameValid = (a: any, value: any, callback: any) => {
  if (value.length < 4) {
    callback(new Error('用户名不能小于4位'))
    return
  }
  if (value.length == 0) {
    callback(new Error('请输入用户名'))
    return
  }
  callback()
}
// 编辑用户的表单验证
const updateUserFormRules = reactive<FormRules>({
  username: [{ required: true, validator: usernameValid }],
})
// 编辑用户的按钮
const editUser = (id: number, name: string) => {
  editUserVisible.value = true
  updateUserForm.username = name
  updateUserForm.id = id
}
// 点击编辑用户中保存的按钮,
const updateUser = () => {
  updateUserFormRef.value?.validate(async (valid) => {
    if (valid) {
      //
      await updateUserApi(updateUserForm)
      ElMessage.success('修改用户成功')
      getUserList()
      editUserVisible.value = false
      updateUserForm.username = ''
      updateUserForm.nickName = ''
    }
  })
}
// 全选
const handleCheckAllChange = (val: boolean) => {
  if (val) {
    selectedRoles.value = allRolesList.value.map((role) => role.id)
    isIndeterminate.value = false
    return
  }
  selectedRoles.value = []
}
// 选择单个 ====改用 watch
watch(
  selectedRoles,
  () => {
    isIndeterminate.value =
      selectedRoles.value.length < allRolesList.value.length &&
      selectedRoles.value.length != 0
        ? true
        : false
    checkAll.value = selectedRoles.value.length === allRolesList.value.length
  },
  { immediate: true }
)
/* const handleCheckedRolesChange = () => {
  console.log(123)
  isIndeterminate.value =
    selectedRoles.value.length < allRolesList.value.length &&
    selectedRoles.value.length != 0
      ? true
      : false
  checkAll.value = selectedRoles.value.length === allRolesList.value.length
} */
// 分配角色的按钮
const assignRoles = async (id: number, name: string) => {
  //  召唤对话框
  assignRoleVisible.value = true
  roleUser.value = name
  userId.value = id
  const res = await getUserRolesApi(id)
  allRolesList.value = res.allRolesList
  selectedRoles.value = res.assignRoles.map((role) => role.id)
}
// 设置角色的对话框关闭
const clearRoleInfo = () => {
  roleUser.value = ''
  userId.value = 0
  // isIndeterminate.value = false
}
// 发送设置角色的请求
const assignRoleToUser = async () => {
  await assignRolesToUserApi(userId.value, selectedRoles.value)
  ElMessage.success('设置用户角色成功')
  assignRoleVisible.value = false
  getUserList()
}

// 表单校验

const passwordValid = (a: any, value: any, callback: any) => {
  if (value.length < 6) {
    callback(new Error('用户名不能小于6位'))
    return
  }
  if (value.length == 0) {
    callback(new Error('请输入用户密码'))
    return
  }
  callback()
}
// 添加用户的表单校验
const addUserFormRules = reactive<FormRules>({
  username: [{ required: true, validator: usernameValid }],
  // nickName: [{ required: true, message: '请输入昵称', trigger: 'blur' }],
  password: [{ required: true, validator: passwordValid }],
})

// 封装请求数据的函数
const getUserList = async () => {
  isLoading.value = true
  const res = await getUserListApi({
    page: currentPage.value,
    limit: pageSize.value,
    username: searchUsername.value,
  })
  isLoading.value = false

  total.value = res.total
  userList.value = res.items
}
// 条件搜索
const searchWithUsername = () => {
  currentPage.value = 1
  getUserList()
}
// 清空搜索条件
const clearSearchUsername = () => {
  searchUsername.value = ''
  getUserList()
}
// 切换页码
const handleSizeChange = (newPageSize: number) => {
  pageSize.value = newPageSize
  getUserList()
}
// 切换当前页
const handleCurrentChange = (newPage: number) => {
  currentPage.value = newPage
  getUserList()
}

// 组件挂载请求数据
onMounted(getUserList)

// 添加用户的按钮
const addUser = () => {
  visible.value = true
}
// 添加用户的对话框关闭清空用户数据
const clearAll = () => {
  userInfo.username = ''
  userInfo.nickName = ''
  userInfo.password = ''
}
// 发送请求添加用户
const saveUser = async () => {
  // 触发表单校验
  addUserFormRef.value?.validate(async (validate) => {
    if (validate) {
      await userSaveApi(userInfo)
      visible.value = false
      ElMessage.success('添加用户成功')
      getUserList()
    }
  })
}
</script>

<style scoped>
.my-20 {
  margin: 20px 0;
}
.inline-block {
  display: inline-block;
  margin-left: 10px;
}
</style>
